import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoserver {                    //服务器代码
    //定义一个Socket对象
    private DatagramSocket socket = null;

    //绑定一个端口，不一定能成功
    public UdpEchoserver(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    //启动服务器
    public void start() throws IOException {
        System.out.println("服务器启动！");
        while(true){
            //1.读取请求并解析
            //2.根据请求计算响应
            //3.响应写回客户端
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);//构造空饭盒
            //DatagramPacket 引用类型
            socket.receive(requestPacket);//盛饭    //没有数据时，会阻塞等待一直到数据传输
            //图方便构造一个String 二进制转换为字符串
            String request = new String(requestPacket.getData(),0, requestPacket.getLength());
            //计算响应
            String response = process(request);
            //返回响应
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length,
                    requestPacket.getSocketAddress() ) ;          //getSocketAddress()同时包含客户端的端口号和ip
            //发送
            socket.send(responsePacket);
            System.out.printf("[%s,%d],req:%s, resp:%s\n",requestPacket.getAddress().toString(),
                    requestPacket.getPort(),request,response);
        }
    }

    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoserver udpEchoServer = new UdpEchoserver(9090);
        udpEchoServer.start();
    }


}

